package com.rd.sys.servlet.auth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.common.utils.crypto.BASE64;
import com.rd.sys.common.utils.crypto.TripleDES;
import com.rd.sys.common.web.session.SessionUtil;
import com.rd.sys.dto.commmon.base.EyeException;
import com.rd.sys.dto.commmon.base.EyeResult;
import com.rd.sys.dto.sys.user.UserInfoDto;
import com.rd.sys.dto.sys.user.UserSecurityDto;
import com.rd.sys.service.sys.user.UserAllInOneService;

public class AnalysisServlet extends AuthBaseServlet {
    private static final long serialVersionUID = 4796712335579501345L;

    private UserAllInOneService userSecurityService = (UserAllInOneService) getService("userAllInOneServiceImpl");

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        EyeResult result = null;
        try {
            /** 1. 从Session中取出用户信息 */
            UserInfoDto userInfo_session = (UserInfoDto) SessionUtil.getSession(req).getAttribute(
                    CommonConstants.UserConstats.USER_SESSION_FLAG);

            if (userInfo_session == null) {
                throw new EyeException(EyeResult.ResultDefine.AUTH_LOGIN_FAIL_USER_NOT_EXIST);
            }

            /** 2. 从http请求中读取客户端发送项目编码和方案编码 */
            BufferedReader reader = null;
            String sendCode = null;
            try {
                reader = new BufferedReader(new InputStreamReader(req.getInputStream(),
                        CommonConstants.SysParamConstants.SYS_CHARSET));

                sendCode = reader.readLine();
            } catch (Exception ex) {
                logger.error("", ex);
                throw new EyeException(EyeResult.ResultDefine.AUTH_LOGIN_READ_REQUEST_ERROR);
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }

            /** 3. 将接收到的字符串解密分解 */
            UserInfoDto userInfo = new UserInfoDto();
            UserSecurityDto userSecurity = null;
            try {
                userInfo.setUsercode(userInfo_session.getUsercode());
                userSecurity = userSecurityService.selectUserSecurityInfo(userInfo);
                if (userSecurity == null) {
                    throw new EyeException(EyeResult.ResultDefine.AUTH_LOGIN_FAIL_USER_NOT_EXIST);
                }
            } catch (Exception ex) {
                logger.error("", ex);
                throw new EyeException(EyeResult.ResultDefine.AUTH_LOGIN_FAIL_USER_NOT_EXIST);
            }

            /** 4. 按协议解析登录信息 */
            String projectCode = null;
            String schemeCode = null;
            try {
                String baseKey = BASE64.decode2String(userSecurity.getBasekey());// 根据安全配置信息中基础密钥解密
                sendCode = TripleDES.decrypt2String(baseKey, BASE64.decode(sendCode)); // 解密

                projectCode = sendCode.split(CommonConstants.UserConstats.AUTH_SPLIT_SIGN)[0];
                schemeCode = sendCode.split(CommonConstants.UserConstats.AUTH_SPLIT_SIGN)[1];
            } catch (Exception ex) {
                logger.error("", ex);
                throw new EyeException(EyeResult.ResultDefine.AUTH_LOGIN_FAIL_PROTOCOL_ERROR);
            }

            /** 5. 鉴权项目和方案存在性 */
            if (!isSchemeExist(userInfo_session.getUsercode(), projectCode, schemeCode)) {
                throw new EyeException(EyeResult.ResultDefine.AUTH_LOGIN_PROJECT_SCHEME_NOTFIND);
            }

            /** 6. 鉴权通过,重定向 */
            String redirectUrl = "http://" + req.getHeader("Host") + req.getContextPath();
            redirectUrl += analysisSchemeUrl + "?theSource=" + CommonConstants.UserConstats.USER_THE_CLIENT_SOURCE;

            /** 7. 先响应结果码,再执行重定向 */
            result = new EyeResult(EyeResult.ResultDefine.COMMON_SUCCESS);
            sendResponse(result, req, resp);

            resp.sendRedirect(redirectUrl);

        } catch (EyeException ex) {
            result = new EyeResult(ex.getResult());
            sendResponse(result, req, resp);
        } catch (Exception ex) {
            logger.error("", ex);
            result = new EyeResult(EyeResult.ResultDefine.AUTH_LOGIN_FAIL);
            sendResponse(result, req, resp);
        }
    }
}
